﻿/***********************************
 * Module             Main Screen
 * Description        
                     window desktop like Main Screen Area 
                     having Top and right expander control 
top  - contain menues
right-> contain you tube video list
center -> clock and other widgets

******************************************/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using VAdvantage.Apps;
using VAdvantage.Utility;
//using VAdvantage.Workspace;

using VAdvantage;
using VAdvantage.DataServiceBasic2;

using SilverlightDesktop.Controls;

namespace Desktop
{
    public partial class MainScreen : UserControl
    {
        #region declarations var and Prop

        /* Main menu Top expander */
        UIElement MainScreenTopMenu = null;
        /* top expander host main menu */
        VExpender topExpander = null;
        /* Right Expander */
        //VExpender rightExpander = null;
        /* You Tube video list Right Panle */
        ListBox lstYT = null;
        /* You tube service client */
        DataServicesBasic2Client ytClient = null;
        /*total page */
        TextBlock txtTotalPage = null;

        /*total Record */
        TextBlock txtFound = null;

        /*Page */
        ComboBox cmbPage = null;
        /* Serach*/
        YTSearch ytSearch = null;
        //RoleCenter rolecenter = null;

        // Cockpit ckPit = null;
        // AccountWizard acctWiz = null;




        /* Page Size */
        private const int PAGE_SIZE = 10;

        /// <summary>
        /// Top expander
        /// </summary>
        public UIElement TopExpander
        {
            get
            {
                return topExpander;
            }
        }

        /// <summary>
        /// Right expander
        /// </summary>
        public UIElement RightExpander
        {
            get
            {
                return rightExpander;
            }
        }

        #endregion

        /// <summary>
        /// std Constructor
        /// </summary>
        public MainScreen()
        {
            InitializeComponent();

            /* Initilize Top Expander */
            topExpander = new VExpender();
            topExpander.Name = "TopConatiner";
            topExpander.Height = 60;
            topExpander.IsExpanded = false;
            topExpander.ExpanderStyle = VExpender.ExpanderStyleEnum.Top;
            topExpander.Loaded += new RoutedEventHandler(topExpander_Loaded);
            Envs.TopExpander = topExpander;
            /* End */

            //Set Right Panel
            SetRightPanel();



            //MainScreenTopMenu.Style = this.Resources["MenuStyle"] as Style;

            Setbusy(true);
            //Load Short Cut
            desktopContainer.Load();
            //Init get u tube video request 
            GetYTVideo(1, "published", "en", "", "", 10, true);
        }

        /// <summary>
        /// Set Right Panel 
        /// </summary>
        private void SetRightPanel()
        {
            //rightExpander = new VExpender();
            //rightExpander.Name = "rightConatiner";
            //rightExpander.Width = 220;
            //rightExpander.IsExpanded = true;
            //rightExpander.ExpanderStyle = VExpender.ExpanderStyleEnum.Right;
            //rightExpander.Margin = new Thickness(0, 60, 0, 20);

            //rightExpander.Loaded += new RoutedEventHandler(topExpander_Loaded);
            // Envs.TopExpander = topExpander;
            //lstYT = new 
            Grid grd = new Grid();
            grd.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });
            grd.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Star) });
            grd.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });

            VExpender ytTop = new VExpender() { DrawBorderAll = true, Height = 70, IsExpanded = false, ExpanderStyle = VExpender.ExpanderStyleEnum.Top, };

            ytSearch = new YTSearch();
            ytSearch.Margin = new Thickness(0, 0, 0, 0);
            ytSearch.Click += new RoutedEventHandler(ytSearch_Click);
            ytTop.Child = ytSearch;
            grd.Children.Add(ytTop);

            lstYT = new ListBox();
            lstYT.Margin = new Thickness(0, 0, 0, 4);
            lstYT.ItemTemplate = this.Resources["YTDataTemplate"] as DataTemplate;
            lstYT.Background = new SolidColorBrush(Colors.Transparent);
            lstYT.BorderThickness = new Thickness(0);
            grd.Children.Add(lstYT);
            Grid.SetRow(lstYT, 1);

            Grid grdBottom = new Grid();
            StackPanel stPage = new StackPanel() { Margin = new Thickness(2), Orientation = Orientation.Horizontal, HorizontalAlignment = System.Windows.HorizontalAlignment.Right };
            txtTotalPage = new TextBlock() { HorizontalAlignment = System.Windows.HorizontalAlignment.Right, VerticalAlignment = System.Windows.VerticalAlignment.Center };
            cmbPage = new ComboBox() { HorizontalAlignment = System.Windows.HorizontalAlignment.Right };
            txtFound = new TextBlock() { Margin = new Thickness(2), HorizontalAlignment = System.Windows.HorizontalAlignment.Left };

            grdBottom.Children.Add(txtFound);

            stPage.Children.Add(cmbPage);
            stPage.Children.Add(txtTotalPage);
            grdBottom.Children.Add(stPage);
            grd.Children.Add(grdBottom);
            Grid.SetRow(grdBottom, 2);
            rightExpander.Child = grd;
        }

        void ytSearch_Click(object sender, RoutedEventArgs e)
        {

            Setbusy(true);
            GetYTVideo(0, ytSearch.GetOrderBy, ytSearch.GetLang, ytSearch.GetSearchText, "", ytSearch.GetPageSize, true);


        }

        /// <summary>
        /// Load Menu in top expander
        /// </summary>
        /// <param name="mainForm"></param>
        public void LoadTopMenu(MainPage mainForm)
        {

            //DynaMicLoad
            Type type = Envs.GetC1ModuleType("VC1Module.UI.FavByRoleControl");
            if (type != null)
            {
                System.Reflection.ConstructorInfo constructor = null;
                try
                {
                    constructor = type.GetConstructor(new Type[] { typeof(IHost) });
                }
                catch (Exception e)
                {
                    //log.Warning("No transaction Constructor for " + type.FullName + " (" + e.ToString() + ")");
                }
                if (constructor != null)
                {
                    try
                    {

                        MainScreenTopMenu = (UIElement)constructor.Invoke(new object[] { mainForm });
                        // container.Children.Add(ig as UIElement);
                    }
                    catch
                    {

                    }
                }
                else
                {
                    //throw new Exception("No Std Constructor");
                }


            }


            //FavByRole favByRole = FavByRole.Get(mainForm);
            //favByRole.GetModule(MainScreenTopMenu);
            WeatherCtrl.LoadWeather();
        }

        #region events

        void topExpander_Loaded(object sender, RoutedEventArgs e)
        {
            if (MainScreenTopMenu != null)
            {
                topExpander.Content = MainScreenTopMenu;
            }
        }


        #endregion

        #region YouTube

        /// <summary>
        /// Get YouTube Video's  
        /// </summary>
        /// <param name="sIndex">page index</param>
        private void GetYTVideo(int sIndex, string orderby, string lang, string search, string videoRange, int pSize, bool reload)
        {
            ytClient = AEnv.GetDataServiceBasic2Client();

            // ytClient.GetStandardYouTubeFeedCompleted += new EventHandler<GetStandardYouTubeFeedCompletedEventArgs>(ytClient_GetStandardYouTubeFeedCompleted);
            ytClient.GetPrivateFeedCompleted += (sender, e) =>
            {
                cmbPage.SelectionChanged -= new SelectionChangedEventHandler(cmbPage_SelectionChanged);
                if (e.Result != null)
                {
                    if (cmbPage.Items.Count == 0 || reload)
                    {
                        cmbPage.Items.Clear();
                        int pages = (e.Result.TotalResults / pSize) + (e.Result.TotalResults % pSize == 0 ? 0 : 1);

                        for (int i = 1; i <= pages; i++)
                        {
                            cmbPage.Items.Add(i.ToString());
                        }
                        if (cmbPage.Items.Count > 0)
                        {
                            cmbPage.SelectedIndex = 0;
                        }
                        txtTotalPage.Text = " " + VAdvantage.Utility.Msg.GetMsg("of") + " " + pages.ToString();

                    }
                    lstYT.ItemsSource = e.Result.Entries;
                    txtFound.Text = e.Result.TotalResults + " " + Msg.GetMsg("ResultFound");

                }
                else
                {
                    lstYT.ItemsSource = null;
                    txtTotalPage.Text = "0";
                    cmbPage.Items.Clear();
                    txtFound.Text = "wrong search criteria or down internet connection";
                }
                cmbPage.SelectionChanged += new SelectionChangedEventHandler(cmbPage_SelectionChanged);
                Setbusy(false);
                ytClient = null;

            };

            //ytClient.GetStandardYouTubeFeedAsync("http://gdata.youtube.com/feeds/api/standardfeeds/most_viewed");
            ytClient.GetPrivateFeedAsync(sIndex, pSize, orderby, lang, search, videoRange);
            ytClient.CloseAsync();
        }

        //void ytClient_GetPrivateFeedCompleted(object sender, GetPrivateFeedCompletedEventArgs e)
        //{
        //    ytClient.GetPrivateFeedCompleted -= new EventHandler<GetPrivateFeedCompletedEventArgs>(ytClient_GetPrivateFeedCompleted);

        //}

        /// <summary>
        /// Set busy UI
        /// </summary>
        /// <param name="isBusy">busy Indicator</param>
        private void Setbusy(bool isBusy)
        {
            cmbPage.IsEnabled = !isBusy;
            ytSearch.IsEnabled = !isBusy;
        }

        void cmbPage_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            int index = cmbPage.SelectedIndex;
            if (index > -1)
            {
                int sIndex = (ytSearch.GetPageSize * index) + 1;
                GetYTVideo(sIndex, ytSearch.GetOrderBy, ytSearch.GetLang, ytSearch.GetSearchText, "", ytSearch.GetPageSize, false);
                Setbusy(true);
            }
            // throw new NotImplementedException();
        }

        void ytClient_GetStandardYouTubeFeedCompleted(object sender, GetStandardYouTubeFeedCompletedEventArgs e)
        {
            ytClient.GetStandardYouTubeFeedCompleted -= new EventHandler<GetStandardYouTubeFeedCompletedEventArgs>(ytClient_GetStandardYouTubeFeedCompleted);
            if (e.Result != null)
            {
                lstYT.ItemsSource = e.Result.Entries;
            }
            ytClient = null;
        }

        SilverlightDesktop.Common.DoubleClickHelper helper = null;

        private void StackPanel_Loaded(object sender, RoutedEventArgs e)
        {
            helper = new SilverlightDesktop.Common.DoubleClickHelper((FrameworkElement)sender, true);
            // helper.DoubleClick += new EventHandler<MouseButtonEventArgs>(helper_DoubleClick);
            helper.Click += new EventHandler<MouseButtonEventArgs>(helper_Click);
            ((FrameworkElement)sender).Loaded -= StackPanel_Loaded;
        }

        void helper_Click(object sender, MouseButtonEventArgs e)
        {
            String id = "";
            if (lstYT.SelectedItem != null)
            {
                id = ((ModelYTEntryInfo)lstYT.SelectedItem).VideoID;
            }
            if (String.IsNullOrEmpty(id))
                return;
            VAdvantage.Dialogs.YTDialog d = new VAdvantage.Dialogs.YTDialog(id);
            d.Show();

        }

        #endregion
    }
}
